package com.sunfeng.chap2.p13;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @Author : 孙峰
 * @Description:   结果说明 文件未被锁定的部分更新成功， 锁定的部位未被更新成功
 * @Date : 2021/10/9  17:55
 */
public class Test13_18 {
    public static void main(String[] args) throws IOException {
        RandomAccessFile randomAccessFile = new RandomAccessFile("d:\\nio\\a.txt", "rw");
        try {
            FileChannel fileChannel = randomAccessFile.getChannel();
            fileChannel.lock(3, 2, true);///// 必须使用共享锁  这是为什么
            System.out.println("A " + fileChannel.position());
            fileChannel.write(ByteBuffer.wrap("1".getBytes())); // index= 0
            System.out.println("B " + fileChannel.position());
            fileChannel.write(ByteBuffer.wrap("2".getBytes())); // index= 1
            System.out.println("C " + fileChannel.position());
            fileChannel.write(ByteBuffer.wrap("3".getBytes())); // index= 2
            System.out.println("D " + fileChannel.position());
            fileChannel.write(ByteBuffer.wrap("4".getBytes())); // index= 3
            System.out.println("E " + fileChannel.position());
            fileChannel.write(ByteBuffer.wrap("5".getBytes())); // index= 4
            System.out.println("F " + fileChannel.position());
            fileChannel.write(ByteBuffer.wrap("6".getBytes())); // index= 5
            System.out.println("G " + fileChannel.position());
            fileChannel.write(ByteBuffer.wrap("7".getBytes())); // index= 6
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
